package com.iamteer.day18.main;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;

import com.iamteer.day18.dao.BookDao;
import com.iamteer.day18.dao.UserDao;
import com.iamteer.day18.model.Book;
import com.iamteer.day18.model.User;

/**
 * 图书管理系统：
 */

class PriceComparator implements Comparator<Book>{
	@Override
	public int compare(Book o1, Book o2) {
		return (int) (o1.getPrice() - o2.getPrice());
	}
}

class AuthorComparator implements Comparator<Book>{
	@Override
	public int compare(Book o1, Book o2) {
		Collator collator = Collator.getInstance();
        return collator.getCollationKey(o1.getAuthor()).compareTo(
            collator.getCollationKey(o2.getAuthor()));
	}
}

class PublishDateComparator implements Comparator<Book>{
	@Override
	public int compare(Book o1, Book o2) {
		return o1.getPublishDate().compareTo(o2.getPublishDate());
	}
}

public class LibrarySystem {

	static Scanner scanner = new Scanner(System.in);
	static UserDao userDao = new UserDao();
	static BookDao bookDao = new BookDao();

	public static final String INPUT_PASSWORD_STRING = "请输入密码：(6～18 位字母或数字)";
	public static final String INPUT_USERNAME_STRING = "请输入账户：(5～18 位字母或数字，首位必须为字母)";
	public static final String MAIN_MENU_STRING = "请选择功能：	（A）用户登录	（B）用户注册	（Q）退出系统";
	public static final String ADMIN_MENU_STRING = "--------请选择功能：\n（A）查看图书	（B）添加图书	（C）修改图书\n"
			+ "（D）删除图书	（E）修改密码	（F）修改用户\n" + "（G）删除用户	（H）查看所有用户	（Q）注销";
	public static final String USER_MENU_STRING = "--------请选择功能：\n（A）查看图书	（B）添加图书	（C）修改图书\n"
			+ "（D）删除图书	（E）修改密码	（Q）注销";

	public static void main(String[] args) {

		startFace();
		userDao.signUp(new User("admin", "111111")); // 测试用，不用每次都注册。。。
		
		Book book1 = new Book();
		book1.setName("Java 入门");
		book1.setAuthor("李四");
		book1.setPublisher("清华出版社");
		book1.setPrice((float) 19.9);
		book1.setIsbn("123402094");
		book1.setPublishDate("2015-12-12");
		bookDao.addBook(book1);
		
		Book book = new Book();
		book.setName("Android入门");
		book.setAuthor("张三");
		book.setPublisher("清华出版社");
		book.setPrice((float) 12.9);
		book.setIsbn("123412094");
		book.setPublishDate("2014-12-12");
		bookDao.addBook(book);

		while (true) {
			System.out.println(MAIN_MENU_STRING);
			String option = scanner.next();
			if ("A".equalsIgnoreCase(option)) {
				int userType = signIn();
				if (userType == UserDao.ADMIN_USER) {
					adminMenu();
				} else if (userType == UserDao.NORMAL_USER) {
					userMenu();
				} else {
					System.out.println("账户或密码错误！");
				}
			} else if ("B".equalsIgnoreCase(option)) {
				signUp();
			} else if ("Q".equalsIgnoreCase(option)) {
				System.out.println("感谢使用本系统，再见！");
				scanner.close();
				System.exit(0);
			}
		}
	}

	public static void startFace() {
		System.out.println("************************************************************");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                    欢迎使用图书管理系                       *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("*                                                          *");
		System.out.println("************************************************************");
	}

	public static void adminMenu() {
		while (true) {
			System.out.println(ADMIN_MENU_STRING);
			String option = scanner.next();
			if ("A".equalsIgnoreCase(option)) { // A）查看图书
				listBooks();
			} else if ("B".equalsIgnoreCase(option)) { // （B）添加图书
				addBook();
			} else if ("C".equalsIgnoreCase(option)) { // （C）修改图书
				editBook();
			} else if ("D".equalsIgnoreCase(option)) { // （D）删除图书
				deleteBook();
			} else if ("E".equalsIgnoreCase(option)) { // （E）修改密码
				changePassword();
			} else if ("F".equalsIgnoreCase(option)) { // （F）修改用户
				changeUsername();
			} else if ("G".equalsIgnoreCase(option)) { // （G）删除用户
				deleteUser();
			} else if ("H".equalsIgnoreCase(option)) { // （H）查看所有用户
				listUsers();
			} else if ("Q".equalsIgnoreCase(option)) { // （Q）注销
				break;
			}

		}
	}

	public static void userMenu() {
		while (true) {
			System.out.println(USER_MENU_STRING);
			String option = scanner.next();
			if ("A".equalsIgnoreCase(option)) { // A）查看图书
				listBooks();
			} else if ("B".equalsIgnoreCase(option)) { // （B）添加图书
				addBook();
			} else if ("C".equalsIgnoreCase(option)) { // （C）修改图书
				editBook();
			} else if ("D".equalsIgnoreCase(option)) { // （D）删除图书
				deleteBook();
			} else if ("E".equalsIgnoreCase(option)) { // （E）修改密码
				changePassword();
			} else if ("Q".equalsIgnoreCase(option)) { // （Q）注销
				break;
			}

		}
	}

	public static int signIn() {
		String username;
		String password;
		System.out.println("请输入登录账户：");
		username = scanner.next();
		System.out.println("请输入登录密码：");
		password = scanner.next();

		User loginUser = new User(username, password);

		return userDao.signIn(loginUser);
	}

	public static boolean signUp() {
		String username;
		String password;

		while (true) {
			System.out.println(INPUT_USERNAME_STRING);
			username = scanner.next();
			if (username.matches("[a-zA-Z][a-zA-Z0-9]{4,17}")) {
				break;
			} else {
				System.out.print("账户不符合规则！\t");
			}
		}
		while (true) {
			System.out.println(INPUT_PASSWORD_STRING);
			password = scanner.next();
			if (password.matches("[a-zA-Z0-9]{6,18}")) {
				break;
			} else {
				System.out.print("密码不符合规则！\t");
			}
		}

		return userDao.signUp(new User(username, password));
	}

	public static void changePassword() {
		System.out.println(INPUT_PASSWORD_STRING);
		String newPassword = scanner.next();
		userDao.changePassword(newPassword);

	}

	public static void changeUsername() {
		System.out.println(INPUT_USERNAME_STRING);
		String newUsername = scanner.next();
		userDao.changeUsername(newUsername);
	}

	public static void deleteUser() {
		System.out.println("请输入要删除的用户名");
		String userName = scanner.next();
		userDao.deleteUser(userName);
	}

	public static void listUsers() {
		ArrayList<User> users = userDao.listUsers();
		if (users.isEmpty()) {
			System.out.println("没有用户。。。");
		} else {
			Iterator<User> iterator = users.iterator();
			while (iterator.hasNext()) {
				User user = (User) iterator.next();
				System.out.println(user);
			}
		}
	}

	public static void listBooks() {
		ArrayList<Book> books = bookDao.listBooks();
		if (books.isEmpty()) {
			System.out.println("没有书。。。");
		} else {
			while (true) {
				System.out.println("请选择查看方式：（A）价格排序	（B）作者排序	（C）出版日期排序	（D）返回上一级");
				String option = scanner.next();
				if ("A".equalsIgnoreCase(option)) {
					Collections.sort(books, new PriceComparator());
					break;
				} else if ("B".equalsIgnoreCase(option)) {
					Collections.sort(books, new AuthorComparator());
					break;
				} else if ("C".equalsIgnoreCase(option)) {
					Collections.sort(books, new PublishDateComparator());
					break;
				} else if ("D".equalsIgnoreCase(option)) {
					break;
				}
			}
			System.out.println("|书名|\t|作者|\t|出版社|\t|价格|\t|书号|\t|出版日期|");
			Iterator<Book> iterator = books.iterator();
			while (iterator.hasNext()) {
				Book book = (Book) iterator.next();
				System.out.println(book);
			}
		}
	}

	public static void addBook() {
		Book book = new Book();

		System.out.println("请输入书名：");
		String name = scanner.next();

		System.out.println("请输入作者：");
		String author = scanner.next();

		System.out.println("请输入出版社：");
		String publisher = scanner.next();

		System.out.println("请输入价格：");
		float price = scanner.nextFloat();

		System.out.println("请输入书号：");
		String isbn = scanner.next();

		System.out.println("请输入出版日期：");
		String publishDate = scanner.next();

		book.setName(name);
		book.setAuthor(author);
		book.setPublisher(publisher);
		book.setPrice(price);
		book.setIsbn(isbn);
		book.setPublishDate(publishDate);

		if (bookDao.addBook(book)) {
			System.out.println("添加成功！");
		} else {
			System.out.println("添加失败！");
		}
	}

	public static void editBook() {
		System.out.println("请输入要修改的书号：");
		String isbn = scanner.next();
		Book book = bookDao.findBook(isbn);
		if (book.equals(null)) {
			System.out.println("没有该书");
			return;
		}
		System.out.println(book);
		System.out.println("请选择要修改的属性:\n（A）书名	（B）作者	（C）出版社	（D）价格	（E）书号（F）出版日期\n（G）返回上一级");
		String option = scanner.next();
		if ("A".equalsIgnoreCase(option)) {
			String name = scanner.next();
			book.setName(name);
		} else if ("B".equalsIgnoreCase(option)) {
			String author = scanner.next();
			book.setAuthor(author);
		} else if ("C".equalsIgnoreCase(option)) {
			String publisher = scanner.next();
			book.setPublisher(publisher);
		} else if ("D".equalsIgnoreCase(option)) {
			float price = scanner.nextFloat();
			book.setPrice(price);
		} else if ("E".equalsIgnoreCase(option)) {
			String newisbn = scanner.next();
			book.setIsbn(newisbn);
		} else if ("F".equalsIgnoreCase(option)) {
			String publishDate = scanner.next();
			book.setPublishDate(publishDate);
		}
	}

	public static void deleteBook() {
		Book book = new Book();
		// System.out.println(book);
		System.out.println("请选择：（A）按书名删除	（B）按作者删除	（C）按书号	（D）返回上一级");
		String option = scanner.next();
		if ("A".equalsIgnoreCase(option)) {
			System.out.println("请输入书名：");
			String name = scanner.next();
			book.setName(name);
		} else if ("B".equalsIgnoreCase(option)) {
			System.out.println("请输入作者：");
			String author = scanner.next();
			book.setAuthor(author);
		} else if ("C".equalsIgnoreCase(option)) {
			System.out.println("请输入书号：");
			String publisher = scanner.next();
			book.setPublisher(publisher);
		} 
		if (bookDao.deleteBook(book)) {
			System.out.println("删除成功！");
		} else {
			System.out.println("删除失败！");
		}
	}
}
